﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Activities;
using System.ComponentModel;
using System.Windows.Markup;
using System.Activities.Presentation.Model;

namespace Vision.Core.ActivityComponents.Assembly
{
    [ContentProperty("Body")]
    [Designer(typeof(AssemblyServiceContextDesigner))]
    public class AssemblyServiceContext : NativeActivity
    {
        System.Reflection.Assembly assemblyObject;

        /// <summary>
        /// 
        /// </summary>
        [Category("Input")]
        [DefaultValue(null)]
        [RequiredArgument]
        public InArgument<string> AssemblyFilePath { get; set; }

        /// <summary>
        /// 
        /// </summary>
        [Category("Input")]
        [DefaultValue(null)]
        [RequiredArgument]
        public InArgument<string> AssemblyFileName { get; set; }

        /// <summary>
        /// 
        /// </summary>
        [Browsable(false)]
        [DefaultValue(null)]
        public Activity Body { get; set; }

        protected override void CacheMetadata(NativeActivityMetadata metadata)
        {
            base.CacheMetadata(metadata);
        }
        
        protected override void Execute(NativeActivityContext context)
        {
            if (this.Body != null)
            {
                string assemblyFile = string.Format("{0}\\{1}", this.AssemblyFilePath.Get(context), this.AssemblyFileName.Get(context));
                
                this.assemblyObject = System.Reflection.Assembly.LoadFrom(assemblyFile);
                context.Properties.Add("5D07EA7B-BF1C-4F15-A3F0-AA2B64588D78", this.assemblyObject);
                context.ScheduleActivity(this.Body, this.OnChildActivityCompleted);
            }
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="context"></param>
        /// <param name="completedInstance"></param>
        private void OnChildActivityCompleted(NativeActivityContext context, ActivityInstance completedInstance)
        {
            context.Properties.Remove("5D07EA7B-BF1C-4F15-A3F0-AA2B64588D78");
            this.assemblyObject = null;
        }
    }
}
